import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { log } from 'console';

@Component({
  selector: 'app-emp-jiagong',
  templateUrl: './emp-jiagong.component.html',
  styleUrls: ['./emp-jiagong.component.scss']
})
export class EmpJiagongComponent implements OnInit {
  isLoading;

  //所有工单数据
  public tempData = [];

  public listOfData = [];//工单文件区数据

  fileInfom;//显示工单对应的文件信息
  isOkLoadingfileInfom;

  public fileList;//选择要上传的文件
  public workName;
  uploader;
  fileName;//文件名
  workerName;//工件名
  link;
  workOrder;//上传对应的工单号
  sheet_order;//工件上传

  public unionorder: any;//工单号,
  public newValue: any;//"新值"
  name;//"表中栏位名称"

  addRemark1;//编辑设计备注
  isOkLoadingRemark;
  designRemark;

  splitJudge: string = ',';

  // 接收要修改的数据
  updateData;

  first: any;//首个19码
  tail: any;//结尾19码
  uploadData; // 上传数据

  public workData = [];
  //意同workData
  public dataWork = [];
  public selCNCData = [];

  isShow = [];
  btnStop = [];
  btnStart = [];

  value;//计时时间值
  totalTime;//数据库中的时间
  time;//页面的时间
  recordRowClick = -1;

  //其他备注
  addOtherRemark;
  isOkLoadingOthRemark;
  RemarkValue;//备注框的值
  workKey;

  showWarning = {};//工件行显示退回图标
  showBigWarning = [];//工单行显示退回图标

  isSendVisible;//送出工件
  isSendOkLoading;

  isFileVisible;//删除文件信息
  isFileOkLoading;
  id;//文件信息id


  timeIndex = 0;
  hour;
  minutes;
  seconds;
  timeKey: any = [];

  unionKey;
  smallKey;
  timeDic = {};
  searchValue = ''; //筛选框输入的内容
  // listOfDisplayData = [];
  bodylist;//搜索取消
  key2;
  sfmtime = new Array;
  dlyy;
  dlyynr;
  dlyysz = [];
  // 工号
  jobNo;
  keykey;
  fileInfom2;
  imglist;
  listfd = [];
  fdkey;

  cdcd;
  fditem;
  addDlyy;
  dlyyadd;
  isSendVisible2;
  //1號機台 2號機台 3號機台 4號機台
  selectStatus = [
    { 'name': 'ALL', 'checked': true, 'select': '' },
    { 'name': '1號機台', 'checked': true, 'select': '1號機 ' },
    { 'name': '2號機台', 'checked': true, 'select': '2號機 ' },
    // { 'name': '3號機台', 'checked': true, 'select': '3號機 ' },
    { 'name': '4號機台', 'checked': true, 'select': '4號機 ' },
    { 'name': '5號機台', 'checked': true, 'select': '5號機 ' },
    { 'name': '6號機台', 'checked': true, 'select': '6號機 ' },
    { 'name': '7號機台', 'checked': true, 'select': '7號機 ' },
    // { 'name': '8號機台', 'checked': true, 'select': '8號機 ' },
    { 'name': '9號 走芯機', 'checked': true, 'select': '9號 走芯機' }
  ];

  // 用于判断某工联单号对应的工单是否已全部送出 key:当前二次加工数据的index，value:对应的工单数据，类型[]
  totalDataForMailSending = new Map<number, Array<Object>>()
  indexForMailSending;
  // 以下数据用于指派工程师后发送邮件
  engineerJobNo = [];
  engineerMail = [];
  mailParamsForSend = {
    "type": '',
    "WorkOrder": "",
    "factory": "",
    "name": "",
    "machine_type": "",
    "quantity": 0,
    "toolway": "",
    "delivery_date": "",
    "emp": [],
    "empAddress":[]
  };

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    public activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.activatedRoute.params.subscribe((data) => {
      if (data) {
        console.log("----------------------------\n", data)
        // this.nameTitle = data.name;
        // console.log(this.nameTitle)
      }
    })
  }

  ngOnInit(): void {
    //获取全部数据
    this.jobNo = this.storage.getStorageData('user').job_no;
    console.log(this.jobNo)
    this.getAllData();
  }

  //获取全部数据
  getAllData() {

    this.axios.axiosPost('QueryUnionOrder', { "stage": 4, "stageValue": 1, 'job_no': this.jobNo, box: this.searchValue })
      .then((data) => {
        if (data) {
          // debugger
          console.log(data)
          this.sfmtime.splice(0, this.sfmtime.length)
          this.listfd = [];

          this.tempData = data['order'];
          this.cdcd = this.tempData.length;

          for (let i = 0; i < this.tempData.length; i++) {
            // this.tempData[i].show = false;
            this.listfd.push(new Array)
            // 实际时间栏位把秒转为小时
            this.tempData[i].ercijiagong_shijian = Number(this.tempData[i].ercijiagong_shijian) / 3600;
            if (this.tempData[i].ercijiagong_shijian > 0.00) {
              this.tempData[i].ercijiagong_shijian = Math.floor((this.tempData[i].ercijiagong_shijian + 0.01) * 100) / 100;
            }
            var b = [];
            this.sfmtime.push(b);
            // debugger
            if (this.tempData[i].tip > 0) {
              this.showBigWarning.push(true);
            } else {
              this.showBigWarning.push(false);
            }

            // 将数据的index存入,值初始化为[]
            this.totalDataForMailSending.set(i,[])
          }
          this.storage.setStorageData('result', this.tempData);
          // this.QueryWorkOrder();
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //查询工单对应的工件信息
  QueryWorkOrder(key,item?) {
    console.log('key: \n'+key);
    console.log('item: \n'+JSON.stringify(item) );


    // if (this.tempData[key].show == true) {
    //   this.tempData[key].show = false;
    // } else {
    //   this.tempData[key].show = true;
    // }
    this.jobNo = this.storage.getStorageData('user').job_no;
    this.unionKey = key;
    this.workKey = key;
    this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.tempData[key].union_order, "status": 4, 'job_no': this.jobNo, "box": this.searchValue })
      .then((data) => {
        console.log('QueryWorkOrder:\n'+data)
        if (data['result'] === 'ok' && data['order'].length > 0) {
          this.listfd[key] = new Array;
          // debugger
          const orderData = data['order'];
          //过滤标准件，只显示加工件
          let a = data['order'].filter((item, i) => { return item.type_flag != 0; })
          this.workData[key] = a;
          this.dataWork = a;
          const tempArr = [];
          const timeDefault = [];
          console.log(this.workData)
          this.sfmtime[key] = [];
          for (var t = 0; t < this.workData[key].length; t++) {
            this.listfd[key].push(new Array)
            var sss = {
              zs: false, sj: "00:00:00", mp: false, jsq: "", ks: "", kg: false
            }
            this.sfmtime[key].push(sss)
            
            if (this.totalDataForMailSending.get(key).length < this.workData[key].length) {
               // 添加对应工单数据
               this.totalDataForMailSending.get(key).push(this.workData[key][t]);
            }
            
          }
          for (let i = 0; i < orderData.length; i++) {
            if (orderData[i]['remark'] !== '') {
              tempArr.push(true);
            } else {
              tempArr.push(false);
            }

            // 给点击的小行数据初始化时间
            timeDefault.push('');

          }

          console.log('this.totalDataForMailSending'+this.totalDataForMailSending);
          this.showWarning[key] = tempArr;
          this.timeDic[this.unionKey] = timeDefault;
          console.log('1111111\n', this.showWarning)
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //CNC机台选择
  selStatus(item) {
    item.checked = !item.checked;
    this.selCNC(item);
  }

  //筛选CNC机台
  selCNC(data) {
    // debugger
    // console.log(data,this.tempData['union_order'])
    // this.axios.axiosPost('QueryCncData', { 'unionorder': this.tempData['union_order'], 'cnc': data.select})
    //   .then((data) => {
    //     console.log(data)
    //     if (data['result'] === 'ok') {
    //       this.tempData = data['order'];
    //     }
    //   })

    // 选中
    if (data.checked) {
      const addCNC = this.dataWork.filter(res => res['cnc_name'] === data.select);
      console.log(addCNC)
      this.selCNCData = this.selCNCData.concat(addCNC);
      console.log(this.selCNCData)
    }
    // 未选中
    if (!data.checked) {
      const deleteCNC = this.workData.filter(res => res['cnc_name'] === data.select);
      console.log(deleteCNC)
      this.selCNCData = this.workData.filter(item => !deleteCNC.some(ele => ele['cnc_name'] === item['cnc_name']));
      console.log(this.selCNCData)
    }
    // this.workData = [];
    this.workData = this.selCNCData;
  }

  //点击设计备注
  addRemark(item) {
    this.updateData = item;
    this.axios.axiosPost("QueryBeizhuInfo").then((data) => {
      this.dlyy = data["order"]
      for (var i = 0; i < this.dlyy.length; i++) {
        this.dlyy[i].show = false
      }
      this.axios.axiosPost('QueryWorkOrder', { 'id': item.id }).then((data) => {
        this.addRemark1 = true;
        this.designRemark = item.machine_remark_2;
        item = data["order"][0]
        console.log(item)
        if (item.machine_remark_2.split(",")) {
          this.designRemark = item.machine_remark_2;
          this.updateData = item;
          this.dlyysz = item.machine_remark_2.split(",");
          for (var i = 0; i < this.dlyysz.length; i++) {
            for (var y = 0; y < this.dlyy.length; y++) {
              if (this.dlyysz[i] == this.dlyy[y].name) {
                this.dlyy[y].show = true;
              }
            }
          }
        }
      })
    })
  }
  //确认添加设计备注
  addRemarkOk() {
    this.isOkLoadingRemark = true;
    this.addRemark1 = false;
    this.isOkLoadingRemark = false;
    console.log("修改大表")
    for (var i = 0; i < this.tempData.length; i++) {
      if (this.updateData.union_order == this.tempData[i].union_order) {
        this.key2 = i;
      }
    }
    this.axios.axiosPost('UpdateWorkOrder', {
      'unionorder': this.updateData.union_order, 'workorder': this.updateData.sheet_order,
      'machine_remark_2': this.dlyynr
    }).then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.QueryWorkOrder(this.key2)
        this.CancelAddRemark()
      }
    })
  }

  //取消添加设计备注
  CancelAddRemark() {
    this.addRemark1 = false;
    for (var i = 0; i < this.dlyy.length; i++) {
      this.dlyy[i].show = false
    }
  }
  bzclick(name) {
    console.log(name)
    console.log(this.dlyy)
    this.dlyysz = []
    for (var i = 0; i < this.dlyy.length; i++) {
      if (this.dlyy[i].show == true) {
        this.dlyysz.push(this.dlyy[i].name)
      }
    }
    this.dlyynr = this.dlyysz.join(",")
    console.log(this.dlyynr)
  }
  currentPageDataChange(qqq) {

  }
  downLoad2(infom) {
    console.log(infom)
    this.fileInfom2 = true;
    this.link = this.axios.domainTest1;
    console.log(this.link)

    if (infom.imagefile) {
      this.imglist = infom.imagefile.split(",")
    } else {
      this.imglist = [];
    }
  }
  CancelShow2() {
    this.fileInfom2 = false;
  }
  ShowOK2() {
    this.fileInfom2 = false;
  }


  //点击图标显示此工单的文件信息
  downLoad(infom) {
    console.log(infom)
    this.fileInfom = true;
    // this.updateData = infom;
    // debugger
    this.workOrder = infom.union_order;
    this.workerName = infom.name;
    this.workName = this.workOrder;
    this.sheet_order = infom.sheet_order;
    console.log(infom.name, this.workOrder)
    if (infom.name !== undefined) {
      this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': infom.name })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            this.listOfData = data['files'];
          }
        })
    } else if (infom.name === undefined) {
      this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.sheet_order })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            this.listOfData = data['files'];
          }
        })
    }
  }

  CancelShow() {
    this.fileInfom = false;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
  }

  //上传文件
  Upload() {
    // debugger
    if (this.uploadData == null)
      return;
    console.log(this.workOrder, this.workerName)
    if (this.workerName !== undefined) {
      this.isLoading = true;
      this.axios.axiosPost('Upload', {
        'unionorder': this.workOrder, 'workorder': this.workerName,
        'filename': this.fileName.files[0]['name'], 'filedata': this.uploadData
      })
        .then((data) => {

          console.log(data)
          if (data['result'] === 'ok') {
            this.isLoading = false;
            alert("上传成功！")
            this.uploadData = null;
            this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.workerName })
              .then((data) => {
                if (data['result'] === 'ok') {
                  this.listOfData = data['files'];
                }
              })

          } else {
            this.isLoading = false;
            alert(data["description"])
          }
        }).catch(function (err) {
          console.log(err)
        })
    } else if (this.workerName === undefined) {
      this.isLoading = true;
      this.axios.axiosPost('Upload', {
        'unionorder': this.workOrder, 'workorder': this.sheet_order,
        'filename': this.fileName.files[0]['name'], 'filedata': this.uploadData
      })
        .then((data) => {

          console.log(data)
          if (data['result'] === 'ok') {
            this.isLoading = false;
            alert("上传成功！")
            this.uploadData = null;
            this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.sheet_order })
              .then((data) => {
                if (data['result'] === 'ok') {
                  this.listOfData = data['files'];
                }
              })

          } else {
            this.isLoading = false;
            alert(data["description"])
          }
        }).catch(function (err) {
          console.log(err)
        })
    }
  }

  //选择要上传的文件名
  openFile(event: any): void {
    // debugger
    this.fileName = event.target; //获取点击得到的对象
    const reader = new FileReader();
    reader.onload = (() => {
      if (reader.result) {
        this.uploadData = reader.result;
        console.log(reader.result);
      }
    });
    reader.readAsDataURL(this.fileName.files[0]);//将文件转为Base64格式
    console.log("hahahaahahahah\n", reader.result)
  }

  handleFileCancel() {
    this.isFileVisible = false;
  }

  downLoadFile(data) {
    console.log(data)
    // debugger
    this.fileName = data.file_name;
    this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
    console.log(this.fileName, this.link)
  }

  //删除文件信息
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data)
    this.id = data.id;
  }

  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          let listData = this.listOfData.filter(res => res['id'] !== this.id)
          this.listOfData = listData;
        }
      })
  }




  //点击行显示计时器
  clickLine(bigkey, key, item2) {
    console.log(bigkey, key);

    if (this.sfmtime[bigkey][key].mp == false) {
      this.sfmtime[bigkey][key].zs = true;
      this.sfmtime[bigkey][key].mp == true;
      console.log(item2);

      if (item2) {
        console.log(item2);
        // console.log("开始");
        this.sfmtime[bigkey][key].jsq = setInterval(() => {
          this.sfmtime[bigkey][key].sj = this.timeof(new Date().getTime() - item2)
        }, 1000)
      }
      console.log(item2);
    }
  }

  //开始计时
  start(bigkey, key, item2) {
    if (this.sfmtime[bigkey][key].kg == false) {
      this.sfmtime[bigkey][key].kg = true;
      if (this.sfmtime[bigkey][key].sj == "00:00:00") {
        this.axios.axiosPost('UpdateWorkOrder', {
          'unionorder': item2.union_order, 'workorder': item2.sheet_order,
          'timestamp': new Date().getTime()
        }).then((data) => {
          console.log(data);
          if (data["result"] == "ok") {
            this.workData[bigkey][key].timestamp = new Date().getTime();
            this.clickLine(bigkey, key, new Date().getTime());
          }
        })

      } else {
        alert("已經開始計時了")
      }
      // this.sfmtime[bigkey][key].ks = new Date().getTime();
      // this.sfmtime[bigkey][key].jsq = setInterval(() => {
      //   this.sfmtime[bigkey][key].sj = this.timeof(new Date().getTime() - this.sfmtime[bigkey][key].ks)
      //   console.log("aaaa")
      // }, 1000)
    } else {
      alert("已經開始計時，請勿重復操作")
    }
  }



  //结束计时
  end(item, bigkey, key) {
    clearInterval(this.sfmtime[bigkey][key].jsq)
    clearInterval(this.sfmtime[bigkey][key].jsq)
    if (item.timestamp || this.sfmtime[bigkey][key].sj != "00:00:00") {
      clearInterval(this.sfmtime[bigkey][key].jsq)
      this.axios.axiosPost('AddWorkTime', { 'unionorder': item.union_order, "id": item.id, 'endtime': new Date().getTime(), "stage": 4 })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            console.log("真棒");
            clearInterval(this.sfmtime[bigkey][key].jsq)
            this.sfmtime[bigkey][key].sj = "00:00:00";
            this.sfmtime[bigkey][key].mp = false;
            this.sfmtime[bigkey][key].kg = false;
            this.sfmtime[bigkey][key].zs = false;
            this.sfmtime[bigkey][key].ks = "";
            this.workData[bigkey][key].timestamp = "";
            console.log(this.workData[bigkey][key].timestamp);

            // this.QueryWorkOrder(bigkey)
          }
        })
    } else {
      alert("此工件未開始計時")
    }



  }
  timeof(data) {
    var s;
    var hours: number;
    // hours=parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    hours = parseInt((data % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)).toString())
    // parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    console.log(hours)
    var minutes = parseInt(((data % (1000 * 60 * 60)) / (1000 * 60)).toString());
    var seconds = parseInt(((data % (1000 * 60)) / 1000).toString());
    s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds);
    console.log(s)
    return s;
  }

  //结束页面生命周期
  ngOnDestroy(): void {

  }

  //退回工件
  return(item, key, a) {
    if (item.timestamp == "") {
      this.keykey = key;
      this.fdkey = a;
      this.fditem = item;
      this.unionorder = item.union_order;
      this.workerName = item.sheet_order;
      console.log(item, this.workerName)
      this.addOtherRemark = true;
      let index = item.remark.indexOf(this.storage.getStorageData('user').name)
      if (index === 0 && item['remark']) {
        this.RemarkValue = item.remark + '\n\n';
      } else {
        this.RemarkValue = this.storage.getStorageData('user').name + ':' + item.remark;
      }
      console.log(this.RemarkValue)
    } else {
      alert("該工件未停止計時")

    }

  }
  handleSendCancel2() {
    this.isSendVisible2 = false;
  }
  sendOk2() {
    this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.fditem.union_order, "name1": "stage", "newValue1": 1, "stageValue": 1, "newValue12": 4, "stageValue2": 0, "name2": "bypass", "newValue2": "false" }).then((data) => {
      console.log(data, "工单状态修改成功了,取消了当前工单状态")
    })
    this.axios.axiosPost('UpdateWorkOrder', { 'unionorder': this.fditem.union_order, 'status': 1 }).then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.addOtherRemark = false;
        this.isSendVisible2 = false;
        location.reload();

      }
    })
      .catch((err) => {
        console.log(err);
      })
  }
  //取消备注
  CancelRemark() {
    this.addOtherRemark = false;
  }

  //添加其他备注（退回）
  RemarkOk() {
    if (this.fditem.bypass != "true") {
      if (this.RemarkValue.length != 0) {
        this.addOtherRemark = false;
        this.isOkLoadingOthRemark = false;
        let content = '';
        content = this.RemarkValue;//姓名+内容
        console.log(content)
        this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 2, "stageValue": 1 }).then((data) => {
          console.log(data, "工单状态修改成功了,增加了加工的状态")
        })
        this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "zuzhuang_endtime", "newValue1": "", "name2": "ercijg_endtime", "newValue2": "", "name3": "jiagong_endtime", "newValue3": "" }).then((data) => {
          console.log(data, "取消组装,二次加工,加工时间栏位,")
        })
        this.axios.axiosPost('UpdateWorkOrder', { 'unionorder': this.unionorder, 'workorder': this.workerName, id: this.fditem["id"], 'remark': content, 'status': 2 }).then((data) => {
          console.log(data)
          if (data["result"] == "ok") {
            this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.unionorder, "type": 1, "status": 4 }).then((data) => {
              console.log(data)
              if (!data["order"] || data["order"].length <= 0) {
                this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 2, "stageValue": 1, "newValue12": 4, "stageValue2": 0 }).then((data) => {
                  console.log(data, "工单状态修改成功了,取消了当前工单状态")
                  location.reload();
                })
              } else {
                this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": this.unionorder, "workorder": this.workerName, status: 4 }).then((data) => {
                  console.log(data);
                  if (data["result"] == "ok") {
                    console.log(data["result"])
                    console.log(data)
                    if (data["order"] == undefined || data["order"].length <= 0) {
                      this.QueryWorkOrder(this.keykey);
                    } else {
                      this.QueryWorkOrder2(this.fditem, this.keykey, this.fdkey)
                    }
                  }
                })
              }
            })
          }
        }).catch((err) => {
          console.log(err)
        })
      } else {
        alert("請輸入退單備註")
      }
    } else {
      this.isSendVisible2 = true;
    }

  }
  //点击工单号显示CNC
  showCNC(item) {
    debugger
    console.log(item)
    const data = {};
    data['union_order'] = item.union_order;
    this.router.navigate(['/CNC', data])
  }

  //送出按钮
  send(item, key, a, itemBig) {
    // console.log(item);
    console.log(itemBig);
    
    // 存储key，为后面指出是哪比数据的工单数据送出了
    this.indexForMailSending = key;

    if (item.engineer_ercijiagong == "") {
      alert("未指派工程師")
    } else {
      if (item.timestamp == "") {
        this.keykey = key;
        this.fditem = item;
        this.fdkey = a;
        this.isSendVisible = true;
        this.unionorder = item.union_order;
        this.workerName = item.sheet_order;
        console.log(this.keykey)
   
        // 点击送出时，此时工单数据个数 >= 1
        // length=1 => 快要全部送出了，提前准备参数
        let length = this.totalDataForMailSending.get(key).length
        if (length == 1) {
          console.log('工单数据个数此时为1! ');
          // 准备邮件发送的参数
          this.mailParamsForSend.type = 'S5';
          this.mailParamsForSend.WorkOrder = itemBig.union_order;
          this.mailParamsForSend.factory = itemBig.factory;
          this.mailParamsForSend.name = itemBig.name;
          this.mailParamsForSend.machine_type = itemBig.machine_type;
          this.mailParamsForSend.quantity = itemBig.quatity;
          this.mailParamsForSend.delivery_date = itemBig.delivery_date;
        }

      } else {
        alert("該工件未停止計時")
      }
    }
  }

  //取消送出
  handleSendCancel() {
    this.isSendVisible = false;
  }

  //确认送出
  sendOk() {
    this.isSendOkLoading = true;
    this.isSendVisible = false;
    this.isSendOkLoading = false;
    // debugger
    this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 5, "stageValue": 1, "name2": "assemble_end_date", "newValue2": "" }).then((data) => {
      console.log(data, "工单状态修改成功了,增加了编程的状态")
    })
    this.axios.axiosPost('UpdateWorkOrder', {
      'unionorder': this.unionorder, 'workorder': this.workerName, id: this.fditem["id"], 'status': 5, "check_date": ""
    }).then((data) => {
      if (data["result"] == "ok") {

        // 每次送出对应工单数据-1，直到工单数据为0，则发送邮件
        this.totalDataForMailSending.get(this.indexForMailSending).length -= 1;              

        this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.unionorder, "type": 1, "status": 4 }).then((data) => {
          console.log(data)
          if (!data["order"] || data["order"].length <= 0) {
            console.log("2222222")
            this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 4, "stageValue": 0, "newValue12": 5, "stageValue2": 1 }).then((data) => {
              console.log(data, "工单状态修改成功了,取消了当前工单状态")
              
              let length = this.totalDataForMailSending.get(this.indexForMailSending).length;
              console.log('this.totalDataForMailSending.get(this.indexForMailSending).length: ' + length);
              if (length == 0) {
                
                console.log('此时已经全部送出! 即将发送邮件的参数为: \n', JSON.stringify(this.mailParamsForSend));
                localStorage.setItem('mailParamsForSend', JSON.stringify(this.mailParamsForSend))
                
                try {
                  this.axios.axiosPost('SendEmail', this.mailParamsForSend).then((data) => {
                    console.log(data['result']);
                    localStorage.setItem('result',data['result'])
                    if (data['result'] === 'ok') {
                      console.log("SendEmailSuccessfully!");
                      localStorage.setItem('mailParamsForSendMessage','SendEmailSuccessfully!')
                    }
                  }).catch(error => {
                    // 处理异常
                    console.log('有异常！');
                    localStorage.setItem('mail异常！',error.message)
                      
                  }).finally(() => {
                    // 重新加载页面
                    location.reload();
                  })
                } catch (error) {
                  localStorage.setItem('mailErrorMessage',error.message)
                } finally {
                    this.engineerJobNo = []
                    this.engineerMail = []
                }

              }
            
            })
          } else {
            this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": this.unionorder, "workorder": this.workerName, status: 4 }).then((data) => {
              console.log(data);
              if (data["result"] == "ok") {
                console.log(data["result"])
                console.log(data)
                if (data["order"] == undefined || data["order"].length <= 0) {
                  this.QueryWorkOrder(this.keykey);
                } else {
                  this.QueryWorkOrder2(this.fditem, this.keykey, this.fdkey)
                }
              }
            })
          }

        })
      } console.log(data)
    }).catch((err) => { console.log(err); })

  }

  //计时器
  setTime(timeIndex, timeDic) {
    // debugger
    // console.log(1111111)
    this.hour = Math.floor(this.timeIndex / 3600);
    this.minutes = Math.floor((this.timeIndex - this.hour * 3600) / 60);
    this.seconds = this.timeIndex - this.hour * 3600 - this.minutes * 60;
    this.hour = this.hour < 10 ? "0" + this.hour : this.hour;
    this.minutes = this.minutes < 10 ? "0" + this.minutes : this.minutes;
    this.seconds = this.seconds < 10 ? "0" + this.seconds : this.seconds;
    this.timeIndex = this.timeIndex + 1;
    // console.log(222222)
    const temptime = (this.hour + ":" + this.minutes + ":" + this.seconds).toString();
    // console.log('temptime ==== \n', temptime);
    timeDic[this.unionKey].splice(this.smallKey, 1, temptime);
    // console.log('水水水水水水水水水水水水  \n', timeDic);
  }

  btn_CNC(data) {
    console.log(data)
    const CNCnum = {};
    CNCnum['select'] = data.select;
    console.log(CNCnum['select'])
    this.router.navigate(['/CNC', CNCnum]);
  }

  //箱号筛选
  search() {
    this.getAllData();
  }

  //点击箱号跳转
  showBox(item) {
    console.log(item)
    const data = {};
    data['box'] = item.box;
    data['unionorder'] = item.unionorder;
    this.router.navigate(['/zhijianChild', data]);
  }
  reset() {
    this.searchValue = '';
    this.getAllData();
  }
  QueryWorkOrder2(a, b, c) {
    console.log("触发", a)
    this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": a.unionorder, "workorder": a.workorder, status: 4 }).then((data) => {
      console.log(data);
      if (data["result"] == "ok") {
        this.listfd[b][c] = data["order"];
      }
    })
  }
  addRemarkDelete() {
    console.log(this.dlyy);
    for (var i = 0; i < this.dlyy.length; i++) {
      if (this.dlyy[i].show == true) {
        this.dlyy[i].show == false;
        this.axios.axiosPost("DeleteBeizhuInfo", { name: this.dlyy[i].name }).then((data => {
          this.addRemark(this.updateData)
        }))
      }
    }


  }
  addRemarkAdd() {
    this.addDlyy = true;

  }
  // 取消——添加————添加设计备注
  addRemarkAddCancel() {
    this.addDlyy = false;
  }
  // 确定——添加————添加设计备注
  addRemarkAddOk() {
    this.addDlyy = false;
    this.axios.axiosPost("AddBeizhuInfo", { name: this.dlyyadd })
      .then((data) => {
        console.log(data);
        if (data['result'] === 'ok') {
          this.addRemark(this.updateData);
        }
      })
      .catch((err) => {
        console.log(err);
      });
    this.addRemarkAddCancel()
    this.dlyyadd = ""
  }
}
